package com.coursehub.exercise.config;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.crypto.SecretKey;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    
    @Value("${jwt.secret}")
    private String jwtSecret;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        log.debug("Processing request: {} {}", request.getMethod(), request.getRequestURI());
        
        // 从网关传递的用户信息
        String userId = request.getHeader("X-User-Id");
        String userAccount = request.getHeader("X-User-Account");
        
        log.debug("X-User-Id: {}, X-User-Account: {}", userId, userAccount);
        
        String authHeader = request.getHeader("Authorization");
        log.debug("Authorization header: {}", authHeader != null ? "Bearer ***" : "null");
        
        // 优先处理网关传递的用户信息
        if (userId != null && userAccount != null) {
            // 创建认证对象
            UsernamePasswordAuthenticationToken authentication = 
                new UsernamePasswordAuthenticationToken(userAccount, null, new ArrayList<>());
            
            // 设置用户ID到认证详情中
            authentication.setDetails(userId);
            
            // 设置到安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 将用户信息设置到请求属性中，供RestTemplate拦截器使用
            request.setAttribute("X-User-Id", userId);
            request.setAttribute("X-User-Account", userAccount);
            
            log.debug("Authentication set for user: {} (ID: {})", userAccount, userId);
        } else if (authHeader != null && authHeader.startsWith("Bearer ")) {
            // 如果没有网关用户信息，尝试处理JWT token
            String token = authHeader.substring(7);
            log.debug("Processing JWT token authentication");
            
            try {
                // 解析JWT token
                SecretKey key = Keys.hmacShaKeyFor(jwtSecret.getBytes(StandardCharsets.UTF_8));
                Claims claims = Jwts.parserBuilder()
                        .setSigningKey(key)
                        .build()
                        .parseClaimsJws(token)
                        .getBody();
                
                String tokenUserAccount = claims.get("userAccount", String.class);
                String userName = claims.get("userName", String.class);
                String userIdFromToken = claims.get("userId", String.class);
                
                if (tokenUserAccount != null && userIdFromToken != null) {
                    // 创建认证对象
                    UsernamePasswordAuthenticationToken authentication = 
                        new UsernamePasswordAuthenticationToken(tokenUserAccount, null, new ArrayList<>());
                    
                    // 设置用户ID到认证详情中
                    authentication.setDetails(userIdFromToken);
                    
                    // 设置到安全上下文
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    
                    // 将用户信息设置到请求属性中
                    request.setAttribute("X-User-Id", userIdFromToken);
                    request.setAttribute("X-User-Account", tokenUserAccount);
                    request.setAttribute("X-User-Name", userName);
                    
                    log.debug("JWT Authentication set for user: {} (ID: {})", tokenUserAccount, userIdFromToken);
                } else {
                    log.warn("JWT token missing required claims: userAccount or userId");
                }
            } catch (Exception e) {
                log.error("JWT token validation failed: {}", e.getMessage());
            }
        } else {
            log.debug("No valid authentication information found");
        }
        
        filterChain.doFilter(request, response);
    }
}